package com.luobu.javaee.email;

import com.luobu.javaee.dao.MailCacheMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    MailCacheMapper mailCacheMapper;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String mailFrom;

    // 只发送文本
    @Override
    public void sendMail(Mail mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(mail.getTo());
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent());
        mailSender.send(message);
        logger.info("Email sent successfully");
    }

    public int generateCode(String email) {
        int code = (int) (Math.random() * 9000 + 1000);
        mailCacheMapper.insert(email, code);
        return code;
    }

    public void removeExpiredCode() {
        mailCacheMapper.deleteExpiredCode();
    }

    public boolean checkCode(String email, String code) {
        String codeInDB = mailCacheMapper.selectCodeByEmail(email);
        if (codeInDB == null) {
            return false;
        }
        int codeInDBI = Integer.parseInt(codeInDB);
        return codeInDBI == Integer.parseInt(code);
    }
}

